<template>
    <div class="fixed inset-0 bg-black/95 z-50 flex items-center justify-center">
        <div class="bg-slate-800 rounded-xl p-6 max-w-md w-full border border-indigo-500/30 tech-card">
            <div class="tech-decorations">
                <div class="tech-corner top-left"></div>
                <div class="tech-corner top-right"></div>
                <div class="tech-corner bottom-left"></div>
                <div class="tech-corner bottom-right"></div>
            </div>

            <h3 class="text-xl font-semibold text-indigo-200 mb-4 glow-text-sm">解锁完整报告</h3>

            <div v-if="step === 'select'">
                <p class="text-slate-300 mb-6">
                    支付 <span class="text-indigo-300 font-semibold">¥{{ price }}</span> 解锁完整九型人格测试报告，包含详细分析和个性化建议
                </p>

                <!-- 兑换码输入区域 -->
                <div class="mb-6 p-4 bg-slate-700/30 rounded-lg border border-indigo-500/20">
                    <h4 class="text-indigo-200 font-medium mb-3">使用兑换码</h4>
                    <div class="flex space-x-2">
                        <input v-model="redemptionCode" type="text" placeholder="请输入兑换码"
                            class="flex-1 px-3 py-2 bg-slate-800 border border-indigo-500/30 rounded-lg text-indigo-200 placeholder-slate-400 focus:outline-none focus:border-indigo-500"
                            @keyup.enter="verifyRedemptionCode" />
                        <button
                            class="px-4 py-2 bg-gradient-to-r from-indigo-600 to-indigo-500 hover:from-indigo-500 hover:to-indigo-400 text-white rounded-lg transition-all"
                            @click="verifyRedemptionCode">
                            {{ verifyingCode ? '验证中...' : '验证' }}
                        </button>
                    </div>
                    <div v-if="codeVerifyResult" class="mt-2 text-sm">
                        <div v-if="codeVerifyResult.valid" class="text-green-400">
                            ✓ 兑换码有效
                        </div>
                        <div v-else class="text-red-400">
                            ✗ {{ codeVerifyResult.message }}
                        </div>
                    </div>
                </div>

                <!-- 分割线 -->
                <div class="flex items-center mb-6">
                    <div class="flex-1 h-px bg-indigo-500/20"></div>
                    <span class="px-3 text-slate-400 text-sm">或选择支付方式</span>
                    <div class="flex-1 h-px bg-indigo-500/20"></div>
                </div>

                <div class="grid  gap-4 mb-6">
                    <div v-for="method in paymentMethods" :key="method.id"
                        class="p-4 bg-slate-700/50 rounded-lg border border-indigo-500/20 cursor-pointer hover:bg-slate-700 transition-all"
                        :class="{
                            '!border-indigo-500': selectedMethod === method.id,
                            'hover:bg-slate-700': selectedMethod !== method.id,
                        }" @click="selectedMethod = method.id">
                        <div class="flex items-center">
                            <!-- <img src="~assets/image/alipay.png" v-if="method.id == 'alipay'" class="w-8 h-8 mr-2" /> -->
                            <img src="~assets/image/wechat.png" v-if="method.id == 'wechat'" class="w-8 h-8 mr-2" />
                            <span class="text-indigo-200">{{ method.name }}</span>
                        </div>
                    </div>
                </div>

                <div class="flex justify-end space-x-3">
                    <button
                        class="px-4 py-2 bg-transparent hover:bg-slate-700 text-indigo-300 border border-indigo-500/30 rounded-lg transition-all"
                        @click="router.push({ name: 'poster', params: { id: id as string } })">
                        稍后再说
                    </button>
                    <button v-if="codeVerifyResult && codeVerifyResult.valid"
                        class="px-4 py-2 bg-gradient-to-r from-green-600 to-green-500 hover:from-green-500 hover:to-green-400 text-white rounded-lg transition-all"
                        @click="useRedemptionCode" :disabled="usingCode">
                        {{ usingCode ? '使用中...' : '使用兑换码' }}
                    </button>
                    <button
                        class="px-4 py-2 bg-gradient-to-r from-indigo-600 to-indigo-500 hover:from-indigo-500 hover:to-indigo-400 text-white rounded-lg disabled:opacity-50"
                        :disabled="!selectedMethod" @click="create">
                        立即支付
                    </button>
                </div>
            </div>

            <div v-if="step === 'paying'" class="text-center">
                <div class="mb-6">
                    <div class="mx-auto w-32 h-32 flex items-center justify-center">
                        <img :src="qrCodeUrl" class="w-full h-full" alt="支付二维码" />
                    </div>
                    <p class="text-indigo-200 mt-4">请使用{{ getMethodName() }}扫码支付</p>
                    <p class="text-indigo-300 font-semibold mt-2">¥{{ price }}</p>
                </div>

                <div class="flex justify-center space-x-3">
                    <button
                        class="px-4 py-2 bg-transparent hover:bg-slate-700 text-indigo-300 border border-indigo-500/30 rounded-lg transition-all"
                        @click="step = 'select'">
                        返回
                    </button>
                    <button
                        class="px-4 py-2 bg-gradient-to-r from-indigo-600 to-indigo-500 hover:from-indigo-500 hover:to-indigo-400 text-white rounded-lg">
                        我已支付
                    </button>
                </div>
            </div>

            <div v-if="step === 'success'" class="text-center">
                <div class="mb-6">
                    <div class="mx-auto w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-green-500" fill="none"
                            viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                        </svg>
                    </div>
                    <p class="text-indigo-200 mt-4">支付成功</p>
                    <p class="text-slate-300 mt-2">您已成功解锁完整报告</p>
                </div>

                <button
                    class="px-4 py-2 bg-gradient-to-r from-indigo-600 to-indigo-500 hover:from-indigo-500 hover:to-indigo-400 text-white rounded-lg"
                    @click="handlePaymentSuccess">
                    {{ view_full_report }}
                </button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { createOrder, payment, toPay, checkPayStatus, createRedemptionOrder, wechatAuthUrl } from '/@/api/frontend/enneagram/index'
import { ElMessage } from 'element-plus'

// 兑换码相关API
import { verifyRedemptionCodeApi, useRedemptionCodeApi } from '/@/api/frontend/enneagram/redemption'

const router = useRouter()
const route = useRoute()
const rawId = route.params.id ?? route.query.id
const id: string = Array.isArray(rawId) ? String(rawId[0] ?? '') : String(rawId ?? '')
const price = ref(0)

// 兑换码相关状态
const redemptionCode = ref('')
const verifyingCode = ref(false)
const usingCode = ref(false)
const codeVerifyResult = ref<{
    valid: boolean
    value?: number
    message?: string
    type?: string
    description?: string
} | null>(null)

if (!id) {
    ElMessage.error('未知id,请确认测试来源')
}
// 验证兑换码
const verifyRedemptionCode = async () => {
    if (!redemptionCode.value.trim()) {
        ElMessage.warning('请输入兑换码')
        return
    }

    verifyingCode.value = true
    codeVerifyResult.value = null

    try {
        const res = await verifyRedemptionCodeApi(redemptionCode.value.trim())
        console.log(res.code)
        if (res.code === 1) {
            codeVerifyResult.value = {
                valid: true,
                value: res.data.value,
                type: res.data.type,
                description: res.data.description
            }
            ElMessage.success('兑换码验证成功')
        } else {
            codeVerifyResult.value = {
                valid: false,
                message: res.msg || '兑换码验证失败'
            }
        }
    } catch (error: any) {
        console.log('兑换码验证错误:', error)
        codeVerifyResult.value = {
            valid: false,
            message: error.msg || '验证失败，请重试'
        }
    } finally {
        verifyingCode.value = false
    }
}

// 使用兑换码
const useRedemptionCode = async () => {
    if (!redemptionCode.value.trim()) {
        ElMessage.warning('请输入兑换码')
        return
    }

    usingCode.value = true

    try {
        // 第一步：创建兑换码订单
        const orderRes = await createRedemptionOrder({ id: Number(id) })
        if (orderRes.code !== 1) {
            ElMessage.error(orderRes.msg || '创建兑换码订单失败')
            return
        }

        // 第二步：使用兑换码
        const res = await useRedemptionCodeApi(redemptionCode.value.trim(), Number(id))
        if (res.code === 1) {
            ElMessage.success('兑换码使用成功！')
            step.value = 'success'
            startCountdown() // 开始倒计时跳转
        } else {
            ElMessage.error(res.msg || '兑换码使用失败')
        }
    } catch (error: any) {
        console.error('兑换码使用流程错误:', error)
        ElMessage.error(error.response?.data?.msg || '使用失败，请重试')
    } finally {
        usingCode.value = false
    }
}

// 在这里弹出一个错误提示层，提示用户没有支付订单

const step = ref('')
const selectedMethod = ref('')
const qrCodeUrl = ref('')
const countdown = ref(0) // 添加倒计时变量
const view_full_report = ref('查看完整报告')
const openid = ref<string>('')
const openidToken = ref<string>('')
const isWechatUA = /micromessenger/i.test(navigator.userAgent)
let countdownTimer: number | null = null // 添加倒计时定时器
const paymentMethods = [
    { id: 'wechat', name: '微信支付', icon: '/assets/image/wxpay.png' },
    // { id: 'alipay', name: '支付宝', icon: '/assets/image/alipay.png' },
]
const orderId = ref('')
// 创建订单
const create = async () => {
    try {
        // 微信内置浏览器下不强制在前端拿openid，后端将决定是否授权
        const res = await createOrder({ id: Number(id), amount: price.value })
        orderId.value = res.data.order_id
        // 请求支付
        const payPayload: any = { order_id: res.data.order_id, payment_method: selectedMethod.value }
        if (selectedMethod.value === 'wechat' && isWechatUA) {
            payPayload.client_type = 'wechat'
            if (openidToken.value) payPayload.openid_token = openidToken.value
            if (openid.value) payPayload.openid = openid.value
        }
        const payRes = await payment(payPayload)

        // 如服务端要求授权，直接跳转到授权URL
        const params = payRes.data?.paymentParams
        if (params?.type === 'oauth' && params?.auth_url) {
            window.location.href = params.auth_url
            return
        }

        // 处理不同类型的支付响应
        handlePaymentResponse(params)

        // 开始轮询订单状态
        startPollingOrderStatus()
    } catch (error) {
        console.error('创建订单失败', error)
        ElMessage.error('支付请求失败，请重试')
    }
}

// 处理不同类型的支付响应
const handlePaymentResponse = (payData: {
    type: string
    payment_method?: string
    qr_code?: string
    payment_url?: string
    payment_data?: any
    payment_html?: string
}) => {
    if (!payData || !payData.type) {
        ElMessage.error('支付数据异常')
        return
    }

    const paymentMethod = payData.payment_method || selectedMethod.value

    // 首先按支付方式分类处理
    if (paymentMethod === 'alipay') {
        // 支付宝支付处理
        handleAlipayPayment(payData)
    } else if (paymentMethod === 'wechat') {
        // 微信支付处理
        handleWechatPayment(payData)
    } else {
        ElMessage.error('不支持的支付方式')
        console.error('未知支付方式:', paymentMethod)
    }
}

// 处理支付宝支付
const handleAlipayPayment = (payData: any) => {
    switch (payData.type) {
        // 支付宝扫码支付
        case 'scan':
            qrCodeUrl.value = payData.qr_code
            step.value = 'paying'
            break

        // 支付宝网页支付
        case 'web':
            // 创建一个临时div来放置支付宝表单
            const divElement = document.createElement('div')
            divElement.innerHTML = payData.payment_html
            document.body.appendChild(divElement)

            // 自动提交表单
            // const form = divElement.querySelector('form')
            // if (form) form.submit()
            break

        // 支付宝手机网站支付
        case 'h5':
            // window.location.href = payData.payment_url || payData.payment_html
            // 创建一个临时div来放置支付宝表单 暂时用web方式一样
            const wapElement = document.createElement('div')
            wapElement.innerHTML = payData.payment_html
            document.body.appendChild(wapElement)
            break

        // 支付宝APP支付
        case 'app':
            if ((window as any).AlipayJSBridge) {
                (window as any).AlipayJSBridge.call('tradePay', {
                    orderStr: payData.payment_data,
                })
            } else {
                ElMessage.error('请在支付宝APP中打开')
            }
            break

        default:
            ElMessage.error('不支持的支付宝支付类型')
            console.error('未知支付宝支付类型:', payData.type)
    }
}

// 处理微信支付
const handleWechatPayment = (payData: any) => {
    switch (payData.type) {
        // 微信扫码支付
        case 'scan':
            qrCodeUrl.value = payData.qr_code
            step.value = 'paying'
            break

        // 微信H5支付
        case 'h5':
            window.location.href = payData.payment_url
            break

        // 微信小程序支付或JSAPI支付
        case 'mini':
        case 'jsapi':
            function onBridgeReady() {
                WeixinJSBridge.invoke('getBrandWCPayRequest', payData.payment_data, function (res: any) {
                    if (res.err_msg === 'get_brand_wcpay_request:ok') {
                        step.value = 'success'
                    } else {
                        ElMessage.error('支付失败，请重试')
                        step.value = 'select'
                    }
                })
            }
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady();
            }
            break

        // 微信APP支付
        case 'app':
            if ((window as any).webkit?.messageHandlers?.wechatPay) {
                (window as any).webkit.messageHandlers.wechatPay.postMessage(payData.payment_data)
            } else if ((window as any).wechatPay) {
                (window as any).wechatPay.startPay(JSON.stringify(payData.payment_data))
            } else {
                ElMessage.error('请在微信APP中打开')
            }
            break

        default:
            ElMessage.error('不支持的微信支付类型')
            console.error('未知微信支付类型:', payData.type)
    }
}

// 获取支付方式名称
const getMethodName = () => {
    const method = paymentMethods.find((m) => m.id === selectedMethod.value)
    return method ? method.name : ''
}

// 处理支付成功
const handlePaymentSuccess = () => router.push({ name: 'result', params: { id: String(id) } })

// 开始倒计时
const startCountdown = (seconds: number = 3) => {
    countdown.value = seconds
    if (countdownTimer) clearInterval(countdownTimer)

    countdownTimer = window.setInterval(() => {
        view_full_report.value = '查看完整报告 ' + countdown.value
        if (countdown.value <= 1) {
            if (countdownTimer) clearInterval(countdownTimer)
            handlePaymentSuccess() // 倒计时结束后自动跳转
        } else {
            countdown.value--
        }
    }, 1000)
}

// 检查订单状态
let pollingTimer: number | null = null
const startPollingOrderStatus = () => {
    pollingTimer = window.setInterval(async () => {
        try {
            const res = await checkPayStatus({ result_id: Number(id) })
            if (res.data.paid === 'Y') {
                if (pollingTimer) clearInterval(pollingTimer)
                step.value = 'success'
                startCountdown() // 支付成功后开始5秒倒计时
            }
        } catch (error) {
            console.error('检查订单状态失败', error)
        }
    }, 1000)
}

onMounted(() => {
    // 进入页面即在微信内置浏览器中进行静默授权，获取 openid_token
    // 不在前端解析 code/state，回调由后端处理并通过 openid_token 返回
    const q = route.query
    if (typeof q.openid_token === 'string') {
        openidToken.value = q.openid_token
    }

    if (isWechatUA && !openidToken.value) {
        const current = window.location.href
        wechatAuthUrl({ redirect: current })
            .then((json: any) => {
                if (json && (json.code === 1 || json.success === true) && json.data?.auth_url) {
                    window.location.href = json.data.auth_url
                }
            })
            .catch((err: any) => {
                console.error('获取授权URL失败', err)
            })
        return
    }

    toPay({ id: Number(id) })
        .then((res) => {
            if (!res.data) {
                ElMessage.error('获取支付信息失败')
                return
            }

            // 处理支付状态
            if (res.data.paid === 'Y') {
                step.value = 'success'
                ElMessage.success('支付已完成')
                startCountdown() // 如果已支付，开始5秒倒计时
            } else if (res.data.paid === 'N') {
                step.value = 'select'
            } else {
                // 处理未知状态
                step.value = 'select'
                ElMessage.warning('支付状态未知，请重新尝试')
            }

            price.value = res.data.price || 999999
        })
        .catch((err) => {
            console.error('支付检查失败:', err)
            // alert('支付检查失败，请联系管理员')
            ElMessage.error(err.msg || '检查支付状态失败')
            // router.back() // 或其他回退逻辑
        })
})

onUnmounted(() => {
    if (pollingTimer) {
        clearInterval(pollingTimer)
    }
    if (countdownTimer) {
        clearInterval(countdownTimer)
    }
})

// TS 全局对象声明，避免调用第三方桥时类型错误
declare global {
    interface Window {
        AlipayJSBridge?: any
        webkit?: { messageHandlers?: any }
        wechatPay?: { startPay?: (payload: string) => void }
    }
}
// 微信内置桥对象声明
declare const WeixinJSBridge: any
</script>

<style scoped lang="scss"></style>
